package com.mapapp.flutter_mapapp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.Utils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mapapp.flutter_mapapp.R;
import com.mapapp.flutter_mapapp.adapter.AddPictureAdapter;
import com.mapapp.flutter_mapapp.adapter.SeparateHouseholdAdapter;
import com.mapapp.flutter_mapapp.application.Constants;
import com.mapapp.flutter_mapapp.application.MyApplication;
import com.mapapp.flutter_mapapp.bean.LogEntity;
import com.mapapp.flutter_mapapp.bean.WaitForUploading;
import com.mapapp.flutter_mapapp.bean.WaitForUploadingDao;
import com.mapapp.flutter_mapapp.http.Url;
import com.mapapp.flutter_mapapp.persenter.SeparateHouseholdPresenter;
import com.mapapp.flutter_mapapp.service.AudioRecordService;
import com.mapapp.flutter_mapapp.util.FTPClientFunctions;
import com.mapapp.flutter_mapapp.util.HorizontalSpaceItemDecoration;
import com.mapapp.flutter_mapapp.util.SelectPhotoUtil;
import com.mapapp.flutter_mapapp.util.SharePreferenceUtil;
import com.mapapp.flutter_mapapp.util.SortableUUID;
import com.mapapp.flutter_mapapp.util.ToastUtils;
import com.mapapp.flutter_mapapp.view.SeparateHouseholdViewInterface;
import com.mapapp.flutter_mapapp.widget.CacheWarnDialog;
import com.mapapp.flutter_mapapp.widget.TitleBar;
import com.mapapp.flutter_mapapp.widget.UploadDataConfirmDialog;
import com.mapapp.flutter_mapapp.widget.UploadDataProgressDialog;
import com.zhihu.matisse.Matisse;

import org.apache.commons.net.ftp.FTPClient;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SeparateHouseholdsActivity extends ImmersiveBaseActivity implements SeparateHouseholdViewInterface {

    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.selected_household)
    TextView selectedHousehold;
    @BindView(R.id.tv_selected_household)
    TextView tvSelectedHousehold;
    @BindView(R.id.separate)
    TextView separate;
    @BindView(R.id.et_amount)
    EditText etAmount;
    @BindView(R.id.household)
    TextView household;
    @BindView(R.id.rv_households)
    RecyclerView rvHouseholds;
    @BindView(R.id.tv_add_remark)
    TextView tvAddRemark;
    @BindView(R.id.et_add_remark)
    EditText etAddRemark;
    @BindView(R.id.tv_add_pictures)
    TextView tvAddPictures;
    @BindView(R.id.rv_add_pictures)
    RecyclerView rvAddPictures;
    @BindView(R.id.scroll_view)
    NestedScrollView scrollView;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    @BindView(R.id.tv_preview)
    TextView tvPreview;

    private UploadDataConfirmDialog dataConfirmDialog;
    private SeparateHouseholdAdapter separateHouseholdAdapter;
    private String address;
    private String regionId;
    private static final int REQUEST_CODE_CHOOSE = 1991;
    final ArrayList<String> mSelected = new ArrayList<>();

    private FTPClientFunctions ftpClientTool;
    private UploadDataProgressDialog uploadDataProgressDialog;

    private WaitForUploading unique;


    private SeparateHouseholdPresenter presenter;

    private String dirName = SortableUUID.randomUUID();

    private String audioDir;

    private AddPictureAdapter pictureAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_separate_households);
        ButterKnife.bind(this);
        presenter = new SeparateHouseholdPresenter(this, this, lifecycleSubject);


        regionId = getIntent().getStringExtra("regionId");
        address = getIntent().getStringExtra("address");
        audioDir = getIntent().getStringExtra("audioDir");


        separateHouseholdAdapter = new SeparateHouseholdAdapter(R.layout.item_separate_household);
        rvHouseholds.setLayoutManager(new LinearLayoutManager(mContext));
        rvHouseholds.setAdapter(separateHouseholdAdapter);

        tvSelectedHousehold.setText(address);

        rvAddPictures.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        rvAddPictures.setNestedScrollingEnabled(false);
        pictureAdapter = new AddPictureAdapter(R.layout.item_add_picture);
        View headerView = LayoutInflater.from(mContext).inflate(R.layout.header_add_picture, rvAddPictures, false);
        pictureAdapter.setHeaderView(headerView, 0, LinearLayout.HORIZONTAL);
        rvAddPictures.setAdapter(pictureAdapter);
        rvAddPictures.addItemDecoration(new HorizontalSpaceItemDecoration(SizeUtils.dp2px(2)));
        headerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (NetworkUtils.isConnected()) {
                    presenter.submitOperateInfo("1", regionId, null, null);
                } else {
                    LogEntity logEntity = new LogEntity();
                    logEntity.setCurrentMills(System.currentTimeMillis());
                    logEntity.setRegionId(regionId);
                    logEntity.setType("3");
                    MyApplication.getInstance().getDaoSession().getLogEntityDao().insert(logEntity);
                }

                SelectPhotoUtil.openPhotoAlbum(SeparateHouseholdsActivity.this, REQUEST_CODE_CHOOSE);
            }
        });

        pictureAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                pictureAdapter.remove(position);
                mSelected.remove(position);
            }
        });

        pictureAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(mContext, PreviewPictureActivity.class);
                intent.putStringArrayListExtra("images", mSelected);
                intent.putExtra("current", position + 1);
                startActivity(intent);
            }
        });

        unique = MyApplication.getInstance().getDaoSession().getWaitForUploadingDao()
                .queryBuilder().where(WaitForUploadingDao.Properties.RegionId.eq(regionId),
                        WaitForUploadingDao.Properties.HostAddress.eq(Url.BASE_URL),
                        WaitForUploadingDao.Properties.UserId.eq(SharePreferenceUtil.get(mContext, Constants.USERNAME, ""))).unique();
        if (unique != null) {
            CacheWarnDialog cacheWarnDialog = new CacheWarnDialog(mContext);
            cacheWarnDialog.showPopupWindow();
            cacheWarnDialog.setListener(new CacheWarnDialog.OnItemClickListener() {

                @Override
                public void onClickUploading() {
                    finish();
                    startActivity(new Intent(mContext, UploadDataActivity.class));
                }

                @Override
                public void onClickContinue() {
                    if (unique.getCategory() == 0 || unique.getCategory() == 2 || unique.getCategory() == 4) {
                        return;
                    }

                    String childPhotosPath = unique.getChildPhotosPath();
                    String childRemark = unique.getChildRemark();

                    etAddRemark.setText(childRemark);
                    dirName = unique.getChildPhotoDirName();
                    etAmount.setText(String.format("%d", unique.getSeparationHouseholdCount()));

                    if (childPhotosPath != null) {
                        String[] pathList = childPhotosPath.split(",");
                        if (pathList.length > 0) {
                            List<String> list = Arrays.asList(pathList);
                            mSelected.addAll(list);
                            pictureAdapter.setNewData(mSelected);
                        }
                    }
                }
            });
        }

        titleBar.getIvBack().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_CHOOSE) {
                if (Matisse.obtainPathResult(data) != null) {
                    mSelected.addAll(Matisse.obtainPathResult(data));
                }
                for (String absolutePath : mSelected) {
                    pictureAdapter.addData(absolutePath);
                }
            }
        }

    }

    private synchronized void upload(final List<String> pathList, final List<String> nameList, final String dirName,
                                     final List<String> audioNames, final String audioDir,
                                     final List<String> childPathList, final List<String> childNameList,
                                     final String childPhotoDir, final WaitForUploading datum) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (ftpClientTool == null) {
                    ftpClientTool = new FTPClientFunctions();
                }

                boolean connectResult = ftpClientTool.ftpConnect(Url.getInstance().ftpServer, Url.getInstance().ftpUsername, Url.getInstance().ftpPassword, Url.getInstance().ftpPort);
                if (connectResult) {
                    final FTPClient ftpClient = ftpClientTool.getFtpClient();
                    try {
                        if (audioNames != null) {
                            ftpClient.changeWorkingDirectory("/radio");
                            ftpClient.makeDirectory(datum.getAudioDirName());
                            boolean radioDir = ftpClient.changeWorkingDirectory("/radio/" + datum.getAudioDirName());
                            if (radioDir) {
                                boolean b = true;
                                for (String audioName : audioNames) {
                                    b = ftpClientTool.ftpUpload(AudioRecordService.FILE_DIR, audioName);
                                    if (!b) {
                                        break;
                                    }
                                }
                                if (b) {
                                    ftpClientTool.ftpUploadList(dirName, pathList, nameList, childPhotoDir, childPathList, childNameList);
                                } else {
                                    showUploadFailed(2);
                                }
                            } else {
                                showUploadFailed(2);
                            }
                        } else {
                            ftpClientTool.ftpUploadList(dirName, pathList, nameList, childPhotoDir, childPathList, childNameList);
                        }
                    } catch (IOException e) {
                        showUploadFailed(2);
                        e.printStackTrace();
                    }
                } else {
                    showUploadFailed(0);
                }

            }
        }).start();

    }

    private void doGet(WaitForUploading datum) {
        switch (datum.getCategory()) {
            case 0:
                presenter.submitProcessNoDialog(datum.getRemark(), datum.getEndTime(), datum.getPhotoDirName(), datum.getProcessId(),
                        datum.getAudioDirName(), datum.getRegionId(), datum.getProcessStartTime(), datum.getState(), datum.getType());
                break;
            case 1:
                presenter.submitSplitRegion(datum.getRegionId(), datum.getSeparationHouseholdCount(), datum.getChildRemark(), datum.getAudioDirName(), datum.getChildPhotoDirName());
                break;
            case 2:
                presenter.submitMergeRegionNoDialog(datum.getRegionId(), datum.getMergedIds(), datum.getChildRemark(), datum.getAudioDirName(), datum.getChildPhotoDirName());
                break;
            case 3:
                presenter.submitProcessNoDialog(datum.getRemark(), datum.getEndTime(), datum.getPhotoDirName(), datum.getProcessId(),
                        datum.getAudioDirName(), datum.getRegionId(), datum.getProcessStartTime(), datum.getState(), datum.getType());

                presenter.submitSplitRegion(datum.getRegionId(), datum.getSeparationHouseholdCount(), datum.getChildRemark(), datum.getAudioDirName(), datum.getChildPhotoDirName());
                break;
            case 4:
                presenter.submitProcessNoDialog(datum.getRemark(), datum.getEndTime(), datum.getPhotoDirName(), datum.getProcessId(),
                        datum.getAudioDirName(), datum.getRegionId(), datum.getProcessStartTime(), datum.getState(), datum.getType());
                presenter.submitMergeRegionNoDialog(datum.getRegionId(), datum.getMergedIds(), datum.getChildRemark(), datum.getAudioDirName(), datum.getChildPhotoDirName());
                break;
        }
    }


    @OnClick({R.id.tv_preview, R.id.tv_submit})
    public void onViewClicked(View view) {
        final String count = etAmount.getText().toString();
        switch (view.getId()) {
            case R.id.tv_preview:
                if (TextUtils.isEmpty(count) || Integer.parseInt(count) > 10) {
                    ToastUtils.showMessage(mContext, "请输入户数且最多10户");
                    return;
                }

                List<String> items = new ArrayList<>();
                for (int i = 0; i < Integer.parseInt(count); i++) {
                    items.add(address + "-" + (i + 1));
                }
                separateHouseholdAdapter.setNewData(items);

                break;
            case R.id.tv_submit:
                if (TextUtils.isEmpty(count) || Integer.parseInt(count) > 10 || Integer.parseInt(count) == 0) {
                    ToastUtils.showMessage(mContext, "请输入正确的户数");
                    return;
                }


                if (dataConfirmDialog == null) {
                    dataConfirmDialog = new UploadDataConfirmDialog(mContext, true);
                }

                dataConfirmDialog.showPopupWindow();

                final WaitForUploading waitForUploading;

                if (unique != null) {
                    waitForUploading = unique;
                    if (!TextUtils.isEmpty(waitForUploading.getAudioName()) &&
                            !waitForUploading.getAudioName().contains(AudioRecordService.audioName)) {
                        waitForUploading.setAudioName(waitForUploading.getAudioName() + "," + AudioRecordService.audioName);
                    }
                    int category = waitForUploading.getCategory();
                    switch (category) {
                        case 0:
                        case 3:
                        case 4:
                            waitForUploading.setCategory(3);
                            break;
                        case 1:
                        case 2:
                            waitForUploading.setCategory(1);
                            break;
                    }
                } else {
                    waitForUploading = new WaitForUploading();
                    waitForUploading.setAudioName(AudioRecordService.audioName);
                    waitForUploading.setAudioPath(AudioRecordService.FILE_DIR);
                    waitForUploading.setCategory(3);
                }

                List<String> pathList = new ArrayList<>();
                List<String> nameList = new ArrayList<>();
                for (String s : mSelected) {
                    pathList.add(s);
                    String uuid = SortableUUID.randomUUID();
                    nameList.add(uuid + ".jpg");
                }

                if (!nameList.isEmpty()) {
                    StringBuilder nameBuilder = new StringBuilder();
                    StringBuilder pathBuilder = new StringBuilder();
                    for (String s : nameList) {
                        nameBuilder.append(s).append(",");
                    }
                    for (String s : pathList) {
                        pathBuilder.append(s).append(",");
                    }
                    nameBuilder.deleteCharAt(nameBuilder.length() - 1);
                    pathBuilder.deleteCharAt(pathBuilder.length() - 1);
                    waitForUploading.setChildPhotosName(nameBuilder.toString());
                    waitForUploading.setChildPhotosPath(pathBuilder.toString());
                }

                waitForUploading.setRegionId(regionId);
                waitForUploading.setUserId((String) SharePreferenceUtil.get(mContext, Constants.USERNAME, ""));
                waitForUploading.setChildRemark(etAddRemark.getText().toString());
                waitForUploading.setAddress(address + " - 分户");
                waitForUploading.setSeparationHouseholdCount(Integer.parseInt(count));
                waitForUploading.setHostAddress(Url.BASE_URL);
                waitForUploading.setChildPhotoDirName(dirName);
                waitForUploading.setAudioDirName(audioDir);

                dataConfirmDialog.setListener(new UploadDataConfirmDialog.OnItemClickListener() {
                    @Override
                    public void onClickSubmit(int state) {
                        String photosPath = waitForUploading.getPhotosPath();
                        String photosName = waitForUploading.getPhotosName();
                        final String audioName = waitForUploading.getAudioName();
                        String childPhotosName = waitForUploading.getChildPhotosName();
                        String childPhotosPath = waitForUploading.getChildPhotosPath();
                        final List<String> pathList;
                        final List<String> nameList;
                        final List<String> audioList;
                        final List<String> childPathList;
                        final List<String> childNameList;
                        if (!TextUtils.isEmpty(photosPath) && !TextUtils.isEmpty(photosName)) {
                            pathList = new ArrayList<>(Arrays.asList(photosPath.split(",")));
                            nameList = new ArrayList<>(Arrays.asList(photosName.split(",")));
                            pathList.add(waitForUploading.getHeadPicPath());
                            nameList.add(waitForUploading.getHeadPicName());
                        } else {
                            if (waitForUploading.getHeadPicPath() != null) {
                                pathList = new ArrayList<>();
                                nameList = new ArrayList<>();
                                pathList.add(waitForUploading.getHeadPicPath());
                                nameList.add(waitForUploading.getHeadPicName());
                            } else {
                                pathList = null;
                                nameList = null;
                            }
                        }
                        if (audioName != null) {
                            audioList = Arrays.asList(audioName.split(","));
                        } else {
                            audioList = null;
                        }

                        if (!TextUtils.isEmpty(childPhotosName) && !TextUtils.isEmpty(childPhotosPath)) {
                            childPathList = Arrays.asList(childPhotosPath.split(","));
                            childNameList = Arrays.asList(childPhotosName.split(","));
                        } else {
                            childPathList = null;
                            childNameList = null;
                        }

                        upload(pathList, nameList, waitForUploading.getPhotoDirName(), audioList,
                                waitForUploading.getAudioDirName(), childPathList, childNameList,
                                waitForUploading.getChildPhotoDirName(), waitForUploading);


                        uploadDataProgressDialog = new UploadDataProgressDialog(mContext);
                        uploadDataProgressDialog.showPopupWindow();

                        ftpClientTool.setListener(new FTPClientFunctions.OnUploadPositionListener() {
                            @Override
                            public void onProgress(final int position, final int total) {
                                Utils.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        uploadDataProgressDialog.setProgress(position, total);
                                    }
                                });
                            }

                            @Override
                            public void onSuccess() {
                                Utils.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        uploadDataProgressDialog.dismiss();
                                        doGet(waitForUploading);
                                    }
                                });
                            }

                            @Override
                            public void onFailed() {
                                try {
                                    if (nameList != null) {
                                        ftpClientTool.getFtpClient().changeToParentDirectory();
                                        boolean b = ftpClientTool.getFtpClient().changeWorkingDirectory("/" + waitForUploading.getPhotoDirName());
                                        if (b) {
                                            for (String s : nameList) {
                                                ftpClientTool.getFtpClient().deleteFile(s);
                                            }
                                        }
                                    }

                                    if (childNameList != null) {
                                        ftpClientTool.getFtpClient().changeToParentDirectory();
                                        boolean b = ftpClientTool.getFtpClient().changeWorkingDirectory("/" + waitForUploading.getChildPhotoDirName());
                                        if (b) {
                                            for (String s : childNameList) {
                                                ftpClientTool.getFtpClient().deleteFile(s);
                                            }
                                        }
                                    }

                                    if (audioList != null) {
                                        ftpClientTool.getFtpClient().changeToParentDirectory();
                                        ftpClientTool.getFtpClient().changeWorkingDirectory("/radio");
                                        boolean b = ftpClientTool.getFtpClient().changeWorkingDirectory("/radio/" + waitForUploading.getAudioDirName());
                                        if (b) {
                                            for (String s : audioList) {
                                                ftpClientTool.getFtpClient().deleteFile(s);
                                            }
                                        }
                                    }
                                    ftpClientTool.ftpDisconnect();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                                Utils.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        uploadDataProgressDialog.dismiss();
                                        ToastUtils.showMessage(mContext, "上传失败");
                                    }
                                });
                            }
                        });
                    }

                    @Override
                    public void onClickSave(int state) {

                        if (NetworkUtils.isConnected()) {
                            presenter.submitOperateInfo("2", waitForUploading.getRegionId(), waitForUploading.getProcessId(), "1");
                        } else {
                            LogEntity logEntity = new LogEntity();
                            logEntity.setCurrentMills(System.currentTimeMillis());
                            logEntity.setProcessId(waitForUploading.getProcessId());
                            logEntity.setRegionId(waitForUploading.getRegionId());
                            logEntity.setFixType("1");
                            logEntity.setType("2");
                            MyApplication.getInstance().getDaoSession().getLogEntityDao().insert(logEntity);
                        }

                        MyApplication.getInstance().getDaoSession().getWaitForUploadingDao().insertOrReplace(waitForUploading);
                        ToastUtils.showMessage(mContext, "保存成功");
                        finish();
                    }
                });

                break;
        }
    }

    private void showUploadFailed(final int state) {
        Utils.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (uploadDataProgressDialog != null) {
                    uploadDataProgressDialog.dismiss();
                }
                ftpClientTool.ftpDisconnect();
                switch (state) {
                    case 0:
                        ToastUtils.showMessage(mContext, "连接文件服务器失败");
                        break;
                    case 1:
                        ToastUtils.showMessage(mContext, "本地照片或录音丢失");
                        break;
                    case 2:
                        ToastUtils.showMessage(mContext, "上传文件失败");
                        break;
                }
            }
        });
    }

    @Override
    public void submitProcessStatus(boolean b, String regionId) {
        ftpClientTool.ftpDisconnect();
        if (b) {
            if (unique != null) {
                MyApplication.getInstance().getDaoSession().getWaitForUploadingDao().delete(unique);
            }
            finish();
        }
    }
}
